package com.henghai.zhenxuan;


import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Instrumentation;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;

import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.data.server.ReleaseServer;
import com.henghai.zhenxuan.exception.RequestHandler;
import com.henghai.zhenxuan.lib.PictureSelectorEngineImp;
import com.henghai.zhenxuan.utils.HttpsUtils;
import com.henghai.zhenxuan.utils.SDKUtil;
import com.hjq.bar.TitleBar;
import com.hjq.bar.style.LightBarStyle;
import com.hjq.http.EasyConfig;
import com.hjq.http.config.IRequestInterceptor;
import com.hjq.http.config.IRequestServer;
import com.hjq.http.model.HttpHeaders;
import com.hjq.http.model.HttpParams;
import com.hjq.http.request.HttpRequest;
import com.kongzue.dialogx.DialogX;
import com.luck.picture.lib.app.IApp;
import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.engine.PictureSelectorEngine;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.TLog;
import com.tamsiree.rxkit.crash.TCrashProfile;
import com.tamsiree.rxkit.crash.TCrashTool;
import com.videogo.openapi.EZOpenSDK;
import com.windmill.sdk.WindMillAd;
import com.windmill.sdk.WindMillConsentStatus;
import com.windmill.sdk.WindMillUserAgeStatus;

import java.lang.reflect.Field;

import okhttp3.OkHttpClient;

public class App extends CustomApplication implements IApp {

    private static final String TAG = "CustomApplication";
    public static Application mInstance = null;

    @SuppressLint("RestrictedApi")
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;

        RxTool.init(this);
        // 关闭崩溃日志上报
        TCrashTool.getConfig().setEnabled(false);
        initHttp();
        PictureAppMaster.getInstance().setApp(this);
        DialogX.init(this);

        initTitleBar();
        SDKUtil.initSDK(getApplicationContext());
        /**
         * 广告初始化必须在主进程中
         */
//        Const.AD.APPKeysMap.put(1,Const.AD.keys1);
//        Const.AD.APPKeysMap.put(2,Const.AD.keys2);
//        Const.AD.APPKeysMap.put(3,Const.AD.keys3);
//        Const.AD.APPKeysMap.put(4,Const.AD.keys4);
//        hookStartActivity();

        // 广告初始化
        if (Const.ISSHOWAD) {
            initSDK();
        }


    }

    private void initTitleBar() {

        TitleBar.setDefaultStyle(new LightBarStyle() {
            @Override
            public TextView newTitleView(Context context) {
                return new AppCompatTextView(context);
            }

            @Override
            public TextView newLeftView(Context context) {
                return new AppCompatTextView(context);
            }

            @Override
            public TextView newRightView(Context context) {
                return new AppCompatTextView(context);
            }
        });
    }

    public static EZOpenSDK getOpenSDK() {
        EZOpenSDK ezOpenSDK = EZOpenSDK.getInstance();
        return ezOpenSDK;
    }

    private void initHttp() {
        // 网络请求框架初始化
        IRequestServer server;
//        if (BuildConfig.DEBUG) {
//            server = new TestServer();
//        } else {
        server = new ReleaseServer();
//        }
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .hostnameVerifier((hostname, session) -> true)
                .build();
        EasyConfig.with(okHttpClient)
                // 是否打印日志
                .setLogEnabled(true)
                // 设置服务器配置（必须设置）
                .setServer(server)
                // 设置请求处理策略（必须设置）
                .setHandler(new RequestHandler(this))
                // 设置请求参数拦截器
                .setInterceptor(new IRequestInterceptor() {
                    @Override
                    public void interceptArguments(@NonNull HttpRequest<?> httpRequest,
                                                   @NonNull HttpParams params,
                                                   @NonNull HttpHeaders headers) {
                        headers.put("Authorization", AppConfig.INSTANCE.getMConfigs().token().get());
                        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
                    }
                })
                // 设置请求重试次数
                .setRetryCount(2)
                // 设置请求重试时间
                .setRetryTime(2000)
                .into();
    }

    @Override
    public Context getAppContext() {
        return null;
    }

    @Override
    public PictureSelectorEngine getPictureSelectorEngine() {
        return new PictureSelectorEngineImp();
    }

    private void initSDK() {

        WindMillAd ads = WindMillAd.sharedAds();

        ads.setUserAge(18);
        ads.setAdult(true);//是否成年
        ads.setPersonalizedAdvertisingOn(true);//是否开启个性化推荐接口
        ads.setIsAgeRestrictedUser(WindMillUserAgeStatus.WindAgeRestrictedStatusNO);//coppa//是否年龄限制
        ads.setUserGDPRConsentStatus(WindMillConsentStatus.ACCEPT);//是否接受gdpr协议

        /**
         * 前置初始化第三方sdk
         */
//        WMNetworkConfig.Builder builder = (new WMNetworkConfig.Builder())
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.ADMOB))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.REKLAMUP))
//                .addInitConfig(new WMAdnInitConfig(23, "appId"))
//                .addInitConfig(new WMAdnInitConfig(24, "appId"))
//                .addInitConfig(new WMAdnInitConfig(25, "appId"))
//                .addInitConfig(new WMAdnInitConfig(26, "appId"))//异步
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.VUNGLE, "appId"))//异步
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.UNITYADS, "appId"))//异步
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.IRONSOURCE, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.TOUTIAO, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.GDT, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.KUAISHOU, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.KLEVIN, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.BAIDU, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.GROMORE, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.ADSCOPE, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.QUMENG, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.PANGLE, "appId"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.APPLOVIN, "appKey"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.APPLOVIN_MAX, "appKey"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.MOBVISTA, "appId", "appKey"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.SIGMOB, "appId", "appKey"))
//                .addInitConfig(new WMAdnInitConfig(WMNetworkConfig.TAPTAP, "appId", "appKey"));
//        ads.setInitNetworkConfig(builder.build());
//        ads.startWithAppId(this, "68741");
        ads.startWithAppId(this, "68741", new WindMillAd.WindMillAdInitListener() {
            @Override
            public void onInitSuccess() {

            }

            @Override
            public void onInitFailed(int errorCode, String errorMsg) {
                Log.d(TAG, "onInitFailed: " + errorCode + " " + errorMsg);
            }
        });
//        Log.d(TAG, "initSDK: " + );
//        ads.startWithAppId(this, "16991",null);
    }

    public static void hookStartActivity() {
        try {
            // 获取ActivityThread类
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            // 获取ActivityThread类中的静态变量sCurrentActivityThread
            Field currentActivityThreadField = activityThreadClass.getDeclaredField("sCurrentActivityThread");
            currentActivityThreadField.setAccessible(true);
            // 获取sCurrentActivityThread字段的值，即ActivityThread的对象
            Object currentActivityThread = currentActivityThreadField.get(null);
            // 获取ActivityThread的mInstrumentation字段
            Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
            mInstrumentationField.setAccessible(true);
            // 获取mInstrumentation对象
            Instrumentation instrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
            // 创建Instrumentation的代理对象
            InstrumentationProxy instrumentationProxy = new InstrumentationProxy(instrumentation);
            // 用InstrumentationProxy替换ActivityThread中的Instrumentation
            mInstrumentationField.set(currentActivityThread, instrumentationProxy);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
